﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Linq;

namespace WindowsFormsDataBaice
{


    /// <summary>
    /// 科室管理窗体
    /// 提供科室信息的树形显示和管理功能
    /// </summary>
    public class DepartmentManagementForm : Form
    {
        // 控件声明
        private TreeView treeDepartments; // 左侧科室树形列表
        private TextBox txtDepartmentName;
        private TextBox txtDepartmentAddress;
        private TextBox txtRegistrationFee;
        private ComboBox cmbCategory; // 病例科别下拉框
        private TextBox txtCaseName; // 病例名称
        private Button btnAdd;
        private Button btnModify;
        private Button btnClear;
        private Button btnAddCase; // 添加病例
        private Button btnDeleteCase; // 删除病例
        private Button btnCancelCase; // 取消病例
        private Button btnRefreshCategories; // 刷新科室按钮
        private Panel pnlLeft; // 左侧面板
        private Panel pnlRight; // 右侧面板
        private Panel pnlInput;
        private Label lblTitle;
        private Label lblDepartmentName;
        private Label lblDepartmentAddress;
        private Label lblRegistrationFee;
        private Label lblCategory; // 科别标签
        private Label lblCaseName; // 病例名称标签
        private Label lblCategoryStatus; // 科别状态标签

        // 数据相关
        private HttpClient httpClient;
        private int selectedDepartmentId = -1;

        public DepartmentManagementForm()
        {
            InitializeComponent();
            SetupEventHandlers();
            httpClient = new HttpClient();
            // 数据加载移到窗体加载事件中
        }

        private void InitializeComponent()
        {
            this.Text = "科室科别增加";
            this.Size = new Size(1200, 800);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.BackColor = Color.FromArgb(240, 240, 240);

            // 标题面板
            Panel titlePanel = new Panel
            {
                Dock = DockStyle.Top,
                Height = 60,
                BackColor = Color.FromArgb(52, 152, 219)
            };

            lblTitle = new Label
            {
                Text = "🏥 科室科别增加",
                Font = new Font("微软雅黑", 16, FontStyle.Bold),
                ForeColor = Color.White,
                Location = new Point(20, 15),
                AutoSize = true
            };

            titlePanel.Controls.Add(lblTitle);
            this.Controls.Add(titlePanel);

            // 主容器面板
            Panel mainPanel = new Panel
            {
                Dock = DockStyle.Fill,
                Padding = new Padding(20)
            };

            // 左侧面板 - 科室树形列表
            pnlLeft = new Panel
            {
                Dock = DockStyle.Left,
                Width = 400,
                BackColor = Color.White,
                BorderStyle = BorderStyle.FixedSingle
            };

            Label lblDepartmentList = new Label
            {
                Text = "科室列表",
                Font = new Font("微软雅黑", 12, FontStyle.Bold),
                Location = new Point(10, 10),
                AutoSize = true
            };

            treeDepartments = new TreeView
            {
                Location = new Point(10, 40),
                Size = new Size(380, 600),
                Font = new Font("微软雅黑", 10),
                ShowLines = true,
                ShowPlusMinus = true,
                ShowRootLines = true,
                FullRowSelect = true,
                HideSelection = false,
                BorderStyle = BorderStyle.FixedSingle
            };

            pnlLeft.Controls.Add(lblDepartmentList);
            pnlLeft.Controls.Add(treeDepartments);

            // 右侧面板
            pnlRight = new Panel
            {
                Dock = DockStyle.Fill,
                BackColor = Color.White
            };

            // 科别信息输入面板
            pnlInput = new Panel
            {
                Dock = DockStyle.Top,
                Height = 250,
                BackColor = Color.White,
                BorderStyle = BorderStyle.FixedSingle
            };

            Label lblSectionTitle = new Label
            {
                Text = "科别",
                Font = new Font("微软雅黑", 12, FontStyle.Bold),
                Location = new Point(20, 20),
                AutoSize = true
            };

            lblDepartmentName = new Label
            {
                Text = "科别名称:",
                Location = new Point(20, 60),
                AutoSize = true
            };

            txtDepartmentName = new TextBox
            {
                Location = new Point(100, 60),
                Size = new Size(200, 25),
                Font = new Font("微软雅黑", 10)
            };

            lblDepartmentAddress = new Label
            {
                Text = "科室地址:",
                Location = new Point(20, 100),
                AutoSize = true
            };

            txtDepartmentAddress = new TextBox
            {
                Location = new Point(100, 100),
                Size = new Size(200, 25),
                Font = new Font("微软雅黑", 10)
            };

            lblRegistrationFee = new Label
            {
                Text = "挂号费:",
                Location = new Point(20, 140),
                AutoSize = true
            };

            txtRegistrationFee = new TextBox
            {
                Location = new Point(100, 140),
                Size = new Size(100, 25),
                Font = new Font("微软雅黑", 10)
            };

            // 科别操作按钮
            btnAdd = new Button
            {
                Text = "添加",
                Location = new Point(320, 60),
                Size = new Size(80, 30),
                BackColor = Color.FromArgb(52, 152, 219),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat
            };

            btnModify = new Button
            {
                Text = "修改科室",
                Location = new Point(320, 100),
                Size = new Size(80, 30),
                BackColor = Color.FromArgb(46, 204, 113),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat
            };

            btnClear = new Button
            {
                Text = "清除",
                Location = new Point(320, 140),
                Size = new Size(80, 30),
                BackColor = Color.FromArgb(149, 165, 166),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat
            };



            // 病例信息面板
            Panel pnlCase = new Panel
            {
                Dock = DockStyle.Top,
                Height = 150,
                BackColor = Color.White,
                BorderStyle = BorderStyle.FixedSingle
            };

            Label lblCaseTitle = new Label
            {
                Text = "病例",
                Font = new Font("微软雅黑", 12, FontStyle.Bold),
                Location = new Point(20, 20),
                AutoSize = true
            };

            lblCategory = new Label
            {
                Text = "科别:",
                Location = new Point(20, 60),
                AutoSize = true
            };

            cmbCategory = new ComboBox
            {
                Location = new Point(100, 60),
                Size = new Size(200, 25),
                Font = new Font("微软雅黑", 10),
                DropDownStyle = ComboBoxStyle.DropDownList,
                BackColor = Color.White,
                ForeColor = Color.Black
            };

            lblCaseName = new Label
            {
                Text = "名称:",
                Location = new Point(20, 100),
                AutoSize = true
            };

            txtCaseName = new TextBox
            {
                Location = new Point(100, 100),
                Size = new Size(200, 25),
                Font = new Font("微软雅黑", 10)
            };

            btnAddCase = new Button
            {
                Text = "添加",
                Location = new Point(320, 60),
                Size = new Size(80, 30),
                BackColor = Color.FromArgb(52, 152, 219),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat
            };

            btnDeleteCase = new Button
            {
                Text = "删除",
                Location = new Point(320, 100),
                Size = new Size(80, 30),
                BackColor = Color.FromArgb(231, 76, 60),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat
            };

            btnCancelCase = new Button
            {
                Text = "取消",
                Location = new Point(420, 100),
                Size = new Size(80, 30),
                BackColor = Color.FromArgb(149, 165, 166),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat
            };

            // 添加刷新按钮
            btnRefreshCategories = new Button
            {
                Text = "刷新",
                Location = new Point(420, 60),
                Size = new Size(80, 30),
                BackColor = Color.FromArgb(52, 152, 219),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat,
                Font = new Font("微软雅黑", 10)
            };


            // 添加状态标签
            lblCategoryStatus = new Label
            {
                Text = "准备中...",
                Font = new Font("微软雅黑", 8),
                ForeColor = Color.Blue,
                Location = new Point(100, 110),
                AutoSize = true
            };

            // 添加控件到面板
            pnlInput.Controls.AddRange(new Control[] {
                lblSectionTitle, lblDepartmentName, txtDepartmentName,
                lblDepartmentAddress, txtDepartmentAddress,
                lblRegistrationFee, txtRegistrationFee,
                btnAdd, btnModify, btnClear
            });

            pnlCase.Controls.AddRange(new Control[] {
                lblCaseTitle, lblCategory, cmbCategory,
                lblCaseName, txtCaseName,
                btnAddCase, btnDeleteCase, btnCancelCase,
                btnRefreshCategories, lblCategoryStatus
            });

            pnlRight.Controls.Add(pnlCase);
            pnlRight.Controls.Add(pnlInput);

            // 添加面板到主容器
            mainPanel.Controls.Add(pnlRight);
            mainPanel.Controls.Add(pnlLeft);

            this.Controls.Add(mainPanel);
        }

        private void SetupEventHandlers()
        {
            // 科室树形列表事件
            treeDepartments.AfterSelect += TreeDepartments_AfterSelect;

            // 科别操作按钮事件
            btnAdd.Click += BtnAdd_Click;
            btnModify.Click += BtnModify_Click;
            btnClear.Click += BtnClear_Click;

            // 病例操作按钮事件
            btnAddCase.Click += BtnAddCase_Click;
            btnDeleteCase.Click += BtnDeleteCase_Click;
            btnCancelCase.Click += BtnCancelCase_Click;

            // 下拉框事件
            cmbCategory.SelectedIndexChanged += CmbCategory_SelectedIndexChanged;

            // 刷新按钮事件
            btnRefreshCategories.Click += BtnRefreshCategories_Click;

            // 窗体事件
            this.Load += DepartmentManagementForm_Load;
        }

        private async void DepartmentManagementForm_Load(object sender, EventArgs e)
        {
            // 窗体加载时的初始化操作
            await LoadDepartmentsAsync(); // 先加载科室数据
            await LoadCategoriesAsync(); // 再加载下拉框数据
            Console.WriteLine("科室科别增加窗体加载完成");
        }

        private async void TreeDepartments_AfterSelect(object sender, TreeViewEventArgs e)
        {
            // 当选择科室树形节点时，加载选中科室的信息到输入框
            if (e.Node != null && e.Node.Tag != null)
            {
                var selectedDepartment = (DepartmentTreeDto)e.Node.Tag;
                selectedDepartmentId = selectedDepartment.Id;

                Console.WriteLine($"选中科室ID: {selectedDepartmentId}, 名称: {selectedDepartment.DepartmentName}");

                // 如果是一级科室（ParentId为0），反填到上方科室管理区域
                if (selectedDepartment.ParentId == 0)
                {
                    txtDepartmentName.Text = selectedDepartment.DepartmentName;
                    txtDepartmentAddress.Text = selectedDepartment.DepartmentAddr ?? "";
                    txtRegistrationFee.Text = selectedDepartment.RegistrationFee.ToString();
                    
                    Console.WriteLine($"一级科室反填到科室管理区域: {selectedDepartment.DepartmentName}");
                }
                // 如果是二级科室（有父级），则反填到下方病例管理区域
                else if (selectedDepartment.ParentId > 0)
                {
                    // 将二级科室名称反填到病例名称字段
                    txtCaseName.Text = selectedDepartment.DepartmentName;
                    
                    // 确保下拉框有数据后再设置选中项
                    if (cmbCategory.Items.Count == 0)
                    {
                        await LoadCategoriesAsync();
                    }
                    
                    SetComboBoxByDepartmentId(selectedDepartment.ParentId);
                    
                    Console.WriteLine($"二级科室反填到病例管理区域: {selectedDepartment.DepartmentName}");
                }
            }
        }

        private async void BtnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证输入
                if (string.IsNullOrWhiteSpace(txtDepartmentName.Text))
                {
                    MessageBox.Show("请输入科别名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (string.IsNullOrWhiteSpace(txtDepartmentAddress.Text))
                {
                    MessageBox.Show("请输入科室地址", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!decimal.TryParse(txtRegistrationFee.Text, out decimal fee))
                {
                    fee = 0; // 默认挂号费为0
                }

                // 准备API请求数据
                var requestData = new
                {
                    DepartmentName = txtDepartmentName.Text.Trim(),
                    DepartmentAddr = txtDepartmentAddress.Text.Trim(),
                    RegistrationFee = fee,
                    Type = "门诊",
                    IsOnline = true,
                    IsEmergencyService = false,
                    ParentId = 0,
                    Remark = ""
                };

                // 调用后端API
                var json = JsonConvert.SerializeObject(requestData);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await httpClient.PostAsync("http://101.201.170.32:5166/api/Departments/AddDepartment", content);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<ApiResult<int>>(responseContent);

                    if (result.Code == 200) // 成功
                    {
                        MessageBox.Show("科别添加成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        ClearInputs();
                        await LoadDepartmentsAsync(); // 重新加载树形数据
                        await LoadCategoriesAsync(); // 重新加载下拉框
                    }
                    else
                    {
                        MessageBox.Show($"添加失败: {result.Msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show($"API调用失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加科别失败: {ex.Message}");
                MessageBox.Show($"添加科别失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void BtnModify_Click(object sender, EventArgs e)
        {
            try
            {
                if (selectedDepartmentId == -1)
                {
                    MessageBox.Show("请先选择要修改的科别", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 验证输入
                if (string.IsNullOrWhiteSpace(txtDepartmentName.Text))
                {
                    MessageBox.Show("请输入科别名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (string.IsNullOrWhiteSpace(txtDepartmentAddress.Text))
                {
                    MessageBox.Show("请输入科室地址", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!decimal.TryParse(txtRegistrationFee.Text, out decimal fee))
                {
                    fee = 0; // 默认挂号费为0
                }

                // 准备API请求数据
                var requestData = new
                {
                    Id = selectedDepartmentId,
                    DepartmentName = txtDepartmentName.Text.Trim(),
                    DepartmentAddr = txtDepartmentAddress.Text.Trim(),
                    RegistrationFee = fee,
                    Type = "门诊",
                    IsOnline = true,
                    IsEmergencyService = false,
                    ParentId = 0,
                    Remark = ""
                };

                // 调用后端API
                var json = JsonConvert.SerializeObject(requestData);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await httpClient.PostAsync("http://101.201.170.32:5166/api/Departments/UpdateDepartment", content);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<ApiResult<int>>(responseContent);

                    if (result.Code == 200) // 成功
                    {
                        MessageBox.Show("科别修改成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        ClearInputs();
                        await LoadDepartmentsAsync(); // 重新加载树形数据
                        await LoadCategoriesAsync(); // 重新加载下拉框
                    }
                    else
                    {
                        MessageBox.Show($"修改失败: {result.Msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show($"API调用失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"修改科别失败: {ex.Message}");
                MessageBox.Show($"修改科别失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnClear_Click(object sender, EventArgs e)
        {
            ClearInputs();
            Console.WriteLine("清空输入框");
        }

        private async void BtnAddCase_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证输入
                if (cmbCategory.SelectedItem == null)
                {
                    MessageBox.Show("请选择科别", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 获取选中的科室ID
                int parentId = 0;
                if (cmbCategory.SelectedValue != null)
                {
                    parentId = Convert.ToInt32(cmbCategory.SelectedValue);
                    Console.WriteLine($"选中的科室ID: {parentId}");
                }
                else
                {
                    Console.WriteLine("下拉框SelectedValue为null，尝试从SelectedItem获取");
                    
                    // 尝试从SelectedItem获取ID
                    if (cmbCategory.SelectedItem != null)
                    {
                        try
                        {
                            var selectedItem = cmbCategory.SelectedItem;
                            var dynamicItem = (dynamic)selectedItem;
                            parentId = dynamicItem.Value;
                            Console.WriteLine($"从SelectedItem获取到科室ID: {parentId}");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"从SelectedItem获取ID失败: {ex.Message}");
                        }
                    }
                }

                // 调试信息：显示下拉框的详细信息
                Console.WriteLine($"下拉框选中项: {cmbCategory.SelectedItem}");
                Console.WriteLine($"下拉框SelectedValue: {cmbCategory.SelectedValue}");
                Console.WriteLine($"下拉框SelectedIndex: {cmbCategory.SelectedIndex}");

                // 准备API请求数据 - 使用科室添加接口
                var requestData = new
                {
                    DepartmentName = txtCaseName.Text.Trim() ?? "未命名病例", // 允许为空，使用默认名称
                    DepartmentAddr = "病例地址", // 设置默认地址避免后端验证失败
                    RegistrationFee = 0,
                    Type = "病例",
                    IsOnline = true,
                    IsEmergencyService = false,
                    ParentId = parentId,
                    Remark = ""
                };

                Console.WriteLine($"发送到后端的数据: {JsonConvert.SerializeObject(requestData)}");

                // 调用后端API
                var json = JsonConvert.SerializeObject(requestData);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await httpClient.PostAsync("http://101.201.170.32:5166/api/Departments/AddDepartment", content);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<ApiResult<int>>(responseContent);

                    if (result.Code == 200) // 成功
                    {
                        MessageBox.Show("病例添加成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        
                        // 清空病例输入框
                        txtCaseName.Text = "";
                        cmbCategory.SelectedIndex = -1;
                        
                        // 重新加载树形数据
                        await LoadDepartmentsAsync();
                        await LoadCategoriesAsync();

                        Console.WriteLine($"添加病例成功：{txtCaseName.Text.Trim()} - 父级ID: {parentId}");
                    }
                    else
                    {
                        MessageBox.Show($"添加失败: {result.Msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show($"API调用失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加病例失败: {ex.Message}");
                MessageBox.Show($"添加病例失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void BtnDeleteCase_Click(object sender, EventArgs e)
        {
            try
            {
                // 检查是否选中了病例（从树形结构中）
                if (selectedDepartmentId == -1)
                {
                    MessageBox.Show("请先在左侧树形结构中选择要删除的病例", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                var result = MessageBox.Show("确定要删除选中的病例吗？", "确认删除",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    Console.WriteLine($"准备删除病例ID: {selectedDepartmentId}");

                    // 准备删除请求数据
                    var deleteRequestData = new
                    {
                        id = selectedDepartmentId,
                        deleteReason = "用户手动删除病例"
                    };

                    // 调用后端API删除病例 - 使用POST请求
                    var deleteUrl = "http://101.201.170.32:5166/api/Departments/DeleteDepartment";
                    Console.WriteLine($"删除API地址: {deleteUrl}");
                    Console.WriteLine($"删除请求数据: {JsonConvert.SerializeObject(deleteRequestData)}");
                    
                    var json = JsonConvert.SerializeObject(deleteRequestData);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    var response = await httpClient.PostAsync(deleteUrl, content);

                    if (response.IsSuccessStatusCode)
                    {
                        var responseContent = await response.Content.ReadAsStringAsync();
                        var deleteResult = JsonConvert.DeserializeObject<ApiResult<int>>(responseContent);

                        if (deleteResult.Code == 200) // 成功
                        {
                            MessageBox.Show("病例删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            
                            // 清空病例输入框
                            txtCaseName.Text = "";
                            cmbCategory.SelectedIndex = -1;
                            selectedDepartmentId = -1;
                            
                            // 重新加载树形数据
                            await LoadDepartmentsAsync();
                            await LoadCategoriesAsync();

                            Console.WriteLine($"删除病例成功，病例ID: {selectedDepartmentId}");
                        }
                        else
                        {
                            MessageBox.Show($"删除失败: {deleteResult.Msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show($"API调用失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除病例失败: {ex.Message}");
                MessageBox.Show($"删除病例失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnCancelCase_Click(object sender, EventArgs e)
        {
            try
            {
                // 清空病例相关输入框
                cmbCategory.SelectedIndex = -1;
                txtCaseName.Text = "";

                Console.WriteLine("取消病例操作，清空输入框");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"取消病例操作失败: {ex.Message}");
            }
        }

        private void CmbCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cmbCategory.SelectedItem != null)
                {
                    string selectedCategory = cmbCategory.SelectedItem.ToString();
                    Console.WriteLine($"选择的科别: {selectedCategory}");
                    
                    // 可以在这里添加根据选择的科别加载相关数据的逻辑
                    // 比如加载该科别的常见病例类型等
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"科别选择改变事件处理失败: {ex.Message}");
            }
        }

        private async void BtnRefreshCategories_Click(object sender, EventArgs e)
        {
            try
            {
                // 重新加载科室下拉框
                await LoadCategoriesAsync();
                MessageBox.Show("科室列表已刷新", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Console.WriteLine("手动刷新科室下拉框");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"刷新科室下拉框失败: {ex.Message}");
                MessageBox.Show($"刷新失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async Task LoadDepartmentsAsync()
        {
            try
            {
                // 调用后端API获取科室列表
                var response = await httpClient.GetAsync("http://101.201.170.32:5115/api/Department/GetDepartmentList");

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonConvert.DeserializeObject<ApiResult<DepartmentListDto>>(responseContent);

                    if (apiResult.Code == 200)
                    {
                        if (apiResult.Data != null && apiResult.Data.Departments != null && apiResult.Data.Departments.Count > 0)
                        {
                            // 构建树形结构
                            BuildDepartmentTree(apiResult.Data.Departments);
                            Console.WriteLine($"科室树形数据加载完成，共 {apiResult.Data.TotalCount} 条记录");
                        }
                        else
                        {
                            // 数据库中没有数据，显示提示
                            MessageBox.Show("数据库中暂无科室数据，请先添加科室信息。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            Console.WriteLine("数据库中暂无科室数据");
                            treeDepartments.Nodes.Clear();
                        }
                    }
                    else
                    {
                        Console.WriteLine($"API返回错误: {apiResult.Msg}");
                        MessageBox.Show($"加载科室数据失败: {apiResult.Msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        treeDepartments.Nodes.Clear();
                    }
                }
                else
                {
                    Console.WriteLine($"API调用失败: {response.StatusCode}");
                    MessageBox.Show($"API调用失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    treeDepartments.Nodes.Clear();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载科室数据失败: {ex.Message}");
                MessageBox.Show($"加载科室数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                treeDepartments.Nodes.Clear();
            }
        }

        private async void LoadDepartments()
        {
            await LoadDepartmentsAsync();
        }

        /// <summary>
        /// 构建科室树形结构
        /// </summary>
        /// <param name="departments">科室树形数据</param>
        private void BuildDepartmentTree(List<DepartmentTreeDto> departments)
        {
            try
            {
                treeDepartments.Nodes.Clear();

                foreach (var dept in departments)
                {
                    // 创建树节点，只显示科室名称
                    var node = new TreeNode(dept.DepartmentName)
                    {
                        Tag = dept
                    };

                    // 递归添加子科室
                    if (dept.Children != null && dept.Children.Count > 0)
                    {
                        AddChildNodes(node, dept.Children);
                    }

                    treeDepartments.Nodes.Add(node);
                }

                // 展开所有节点
                treeDepartments.ExpandAll();

                Console.WriteLine($"树形结构构建完成，共 {departments.Count} 个顶级科室");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"构建树形结构失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 递归添加子节点
        /// </summary>
        /// <param name="parentNode">父节点</param>
        /// <param name="children">子科室列表</param>
        private void AddChildNodes(TreeNode parentNode, List<DepartmentTreeDto> children)
        {
            foreach (var child in children)
            {
                var childNode = new TreeNode(child.DepartmentName)
                {
                    Tag = child
                };

                // 递归添加子节点
                if (child.Children != null && child.Children.Count > 0)
                {
                    AddChildNodes(childNode, child.Children);
                }

                parentNode.Nodes.Add(childNode);
            }
        }

        private async Task LoadCategoriesAsync()
        {
            try
            {
                Console.WriteLine("开始加载下拉框数据...");
                
                // 更新状态
                lblCategoryStatus.Text = "加载中...";
                lblCategoryStatus.ForeColor = Color.Blue;

                // 动态获取所有科室作为下拉框选项
                cmbCategory.Items.Clear();

                // 首先尝试从API获取科室列表
                            Console.WriteLine("正在调用API: http://101.201.170.32:5115/api/Department/GetAllDepartments");
            var response = await httpClient.GetAsync("http://101.201.170.32:5115/api/Department/GetAllDepartments");

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"API响应: {responseContent}");
                    
                    var apiResult = JsonConvert.DeserializeObject<ApiResult<List<DepartmentTreeDto>>>(responseContent);

                    if (apiResult.Code == 200 && apiResult.Data != null)
                    {
                        Console.WriteLine($"API返回成功，数据条数: {apiResult.Data.Count}");
                        
                        // 只添加一级科室数据到下拉框，存储科室ID
                        foreach (var dept in apiResult.Data)
                        {
                            Console.WriteLine($"添加科室到下拉框: {dept.DepartmentName} (ID: {dept.Id})");
                            cmbCategory.Items.Add(new { Text = dept.DepartmentName, Value = dept.Id });
                        }

                        // 设置下拉框显示属性
                        cmbCategory.DisplayMember = "Text";
                        cmbCategory.ValueMember = "Value";

                        // 不自动选择第一项，保持为空
                        cmbCategory.SelectedIndex = -1;

                        // 更新状态
                        lblCategoryStatus.Text = $"已加载 {cmbCategory.Items.Count} 个一级科室";
                        lblCategoryStatus.ForeColor = Color.Green;

                        Console.WriteLine($"科别下拉框从API加载完成，共 {cmbCategory.Items.Count} 个一级科室选项");
                        
                        // 调试：显示下拉框中的所有项目
                        for (int i = 0; i < cmbCategory.Items.Count; i++)
                        {
                            var item = cmbCategory.Items[i];
                            Console.WriteLine($"下拉框项目 {i}: {item}");
                        }
                    }
                    else
                    {
                        Console.WriteLine($"API返回失败: Code={apiResult.Code}, Msg={apiResult.Msg}");
                        // API调用失败，从树形结构中获取
                        LoadCategoriesFromTree();
                    }
                }
                else
                {
                    Console.WriteLine($"API调用失败: {response.StatusCode}");
                    // API调用失败，从树形结构中获取
                    LoadCategoriesFromTree();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"从API加载科别下拉框失败: {ex.Message}");
                // 从树形结构中获取
                LoadCategoriesFromTree();
            }
        }

        private async void LoadCategories()
        {
            await LoadCategoriesAsync();
        }

        /// <summary>
        /// 从树形结构中加载科室到下拉框
        /// </summary>
        private void LoadCategoriesFromTree()
        {
            try
            {
                // 从树形结构中获取所有科室名称
                var allDepartments = GetAllDepartmentsFromTree();

                if (allDepartments.Count > 0)
                {
                    // 只添加一级科室（ParentId为0或null的科室）
                    foreach (var dept in allDepartments)
                    {
                        if (dept.ParentId == 0) // 只添加一级科室
                        {
                            cmbCategory.Items.Add(new { Text = dept.DepartmentName, Value = dept.Id });
                        }
                    }

                    // 设置下拉框显示属性
                    cmbCategory.DisplayMember = "Text";
                    cmbCategory.ValueMember = "Value";

                    // 不自动选择第一项，保持为空
                    cmbCategory.SelectedIndex = -1;

                    // 更新状态
                    lblCategoryStatus.Text = $"已加载 {cmbCategory.Items.Count} 个一级科室";
                    lblCategoryStatus.ForeColor = Color.Green;

                    Console.WriteLine($"科别下拉框从树形结构加载完成，共 {cmbCategory.Items.Count} 个一级科室选项");
                }
                else
                {
                    // 如果没有科室数据，添加一些默认的科室选项
                    LoadDefaultCategories();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"从树形结构加载科别下拉框失败: {ex.Message}");
                // 加载默认科室选项
                LoadDefaultCategories();
            }
        }

        /// <summary>
        /// 加载默认的科室选项（无数据时的处理）
        /// </summary>
        private void LoadDefaultCategories()
        {
            try
            {
                // 不添加任何默认数据，保持下拉框为空
                cmbCategory.Items.Clear();

                // 不自动选择第一项，保持为空
                cmbCategory.SelectedIndex = -1;

                // 更新状态
                lblCategoryStatus.Text = "无科室数据";
                lblCategoryStatus.ForeColor = Color.Orange;

                Console.WriteLine("科别下拉框无数据，保持为空");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理无数据状态失败: {ex.Message}");
                lblCategoryStatus.Text = "加载失败";
                lblCategoryStatus.ForeColor = Color.Red;
            }
        }

        /// <summary>
        /// 从树形结构中获取所有科室
        /// </summary>
        /// <returns>所有科室列表</returns>
        private List<DepartmentTreeDto> GetAllDepartmentsFromTree()
        {
            var allDepartments = new List<DepartmentTreeDto>();

            foreach (TreeNode node in treeDepartments.Nodes)
            {
                CollectDepartmentsFromNode(node, allDepartments);
            }

            return allDepartments;
        }

        /// <summary>
        /// 递归收集节点中的所有科室
        /// </summary>
        /// <param name="node">树节点</param>
        /// <param name="departments">科室列表</param>
        private void CollectDepartmentsFromNode(TreeNode node, List<DepartmentTreeDto> departments)
        {
            if (node.Tag != null)
            {
                departments.Add((DepartmentTreeDto)node.Tag);
            }

            foreach (TreeNode childNode in node.Nodes)
            {
                CollectDepartmentsFromNode(childNode, departments);
            }
        }

        /// <summary>
        /// 根据科室ID设置下拉框选中项
        /// </summary>
        /// <param name="departmentId">科室ID</param>
        private void SetComboBoxByDepartmentId(int departmentId)
        {
            try
            {
                // 从树形结构中查找指定ID的科室
                var allDepartments = GetAllDepartmentsFromTree();
                var targetDepartment = allDepartments.FirstOrDefault(d => d.Id == departmentId);

                if (targetDepartment != null)
                {
                    Console.WriteLine($"查找科室ID: {departmentId}, 科室名称: {targetDepartment.DepartmentName}");
                    Console.WriteLine($"下拉框项目数量: {cmbCategory.Items.Count}");

                    // 遍历下拉框项目，找到匹配的科室ID
                    for (int i = 0; i < cmbCategory.Items.Count; i++)
                    {
                        var item = cmbCategory.Items[i];
                        Console.WriteLine($"下拉框项目 {i}: {item}");
                        
                        try
                        {
                            var dynamicItem = (dynamic)item;
                            Console.WriteLine($"动态项目 Value: {dynamicItem.Value}, Text: {dynamicItem.Text}");
                            if (dynamicItem.Value == departmentId)
                            {
                                cmbCategory.SelectedIndex = i;
                                Console.WriteLine($"成功设置下拉框选中项: {targetDepartment.DepartmentName}");
                                return;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"处理下拉框项目失败: {ex.Message}");
                        }
                    }

                    Console.WriteLine($"未在下拉框中找到科室ID: {departmentId}");
                }
                else
                {
                    Console.WriteLine($"未找到ID为 {departmentId} 的科室");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"设置下拉框选中项失败: {ex.Message}");
            }
        }

        private void ClearInputs()
        {
            // 清空科室管理区域
            txtDepartmentName.Text = "";
            txtDepartmentAddress.Text = "";
            txtRegistrationFee.Text = "";
            
            // 清空病例管理区域
            cmbCategory.SelectedIndex = -1;
            txtCaseName.Text = "";
            
            selectedDepartmentId = -1;
            Console.WriteLine("清空所有输入框");
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            httpClient?.Dispose();
            Console.WriteLine("科室科别增加窗体关闭");
        }
    }
}